package fr.bitstrip.sitn.security;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;




import fr.bitstrip.sitn.dao.UtilisateurDAO;
import fr.bitstrip.sitn.model.Utilisateur;

@SuppressWarnings("serial")
public class BitstripAuthenticationProvider implements AuthenticationProvider {
        @Autowired
        private UtilisateurDAO utilisateurDAO;
        
        public Authentication authenticate(Authentication authentication) throws AuthenticationException 
        {
                String email = (String) authentication.getPrincipal();
                String password = (String) authentication.getCredentials();
                Utilisateur utilisateur = utilisateurDAO.getUserByEmail(email);
                
                if (utilisateur != null && !utilisateur.getPassword().equals(""))
                {
                        if (utilisateur.getPassword().equals(password)) {
                                final GrantedAuthority gai = new GrantedAuthority() {
                                        public String getAuthority() {
                                                return "ROLE_USER";
                                        }                                               
                                };
                                    
                                List<GrantedAuthority> authorithies = new ArrayList<GrantedAuthority>();
                                authorithies.add(gai);
                                
                                return new UsernamePasswordAuthenticationToken(email, password, authorithies);
                        }
                }
                
                throw new BadCredentialsException("Mauvaise authentification : " + email);
        }
        
        public boolean supports(Class aclass) {
                return true;
        }
}
